package com.example.kkblog.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.kkblog.controller.dto.ResponseDto;
import com.example.kkblog.domain.Follow;
import com.example.kkblog.domain.dto.ArticlePreDto;
import com.example.kkblog.domain.dto.DynamicPreDto;
import com.example.kkblog.domain.dto.UserDto;
import com.example.kkblog.domain.query.StarQuery;
import com.example.kkblog.domain.query.UserQuery;
import com.example.kkblog.mapper.*;
import com.example.kkblog.service.KKBlogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.Objects;

/**
 * @Author xiaoke
 * @Date 2024 04 16 19 59
 **/
@Controller
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private DynamicMapper dynamicMapper;

    @Autowired
    private DynamicCommentMapper dynamicCommentMapper;

    @Autowired
    private FollowMapper followMapper;

    @Autowired
    private KKBlogService kkBlogService;

    @Autowired
    private LikeMapper likeMapper;

    @Autowired
    private ArticleMapper articleMapper;

    @Autowired
    private StarMapper starMapper;

    @GetMapping("/me")
    public String me(HttpSession session, Model model) {
        UserDto loginUser = (UserDto) session.getAttribute("user");
        return userPage(loginUser.getId(), session, model);
    }

    @GetMapping("/stars")
    public String star(HttpSession session, Model model) {
        UserDto loginUser = (UserDto) session.getAttribute("user");
        UserDto userDto = userMapper.selectUserDtoByUserId(loginUser.getId());
        getUserPageInfo(loginUser, userDto, model);

        // 查询用户的动态
        List<DynamicPreDto> dynamics = starMapper.selectStarDynamics(new StarQuery(userDto.getId(), null, 5));
        // 查询是否对用户的动态点赞
        dynamics.forEach(item -> {
            item.setLiked(likeMapper.selectIfUserLike(loginUser.getId() + "_" + item.getId()) > 0);
        });
        getUserPageInfo(loginUser, userDto, model);
        model.addAttribute("dynamics", dynamics);
        return "user/user-stars";
    }

    @GetMapping("/{id}/articles")
    public String articles(@PathVariable Integer id, HttpSession session, Model model) {
        UserDto loginUser = (UserDto) session.getAttribute("user");
        UserDto userDto = userMapper.selectUserDtoByUserId(id);
        // 查询用户的文章
        List<ArticlePreDto> articlePreDtos = articleMapper.selectByUserId(id);
        getUserPageInfo(loginUser, userDto, model);
        model.addAttribute("articles", articlePreDtos);
        return "user/user-articles";
    }

    @GetMapping("/{id}/fans")
    public String fans(@PathVariable Integer id, HttpSession session, Model model) {
        UserDto loginUser = (UserDto) session.getAttribute("user");
        UserDto userDto = userMapper.selectUserDtoByUserId(id);
        getUserPageInfo(loginUser, userDto, model);

        // 查询用户的粉丝
        List<UserDto> fans = followMapper.selectFans(new UserQuery(userDto.getId(), null, 10));
        model.addAttribute("allFans", fans);
        if (loginUser != null) {
            // 查询自己的关注列表
            List<Integer> followingIds = followMapper.selectFollowedIds(loginUser.getId());
            fans.forEach(item -> item.setFollow(followingIds.contains(item.getId())));
        }

        return "user/user-fans";
    }

    @GetMapping("/{id}/follows")
    public String follows(@PathVariable Integer id, HttpSession session, Model model) {
        UserDto loginUser = (UserDto) session.getAttribute("user");
        UserDto userDto = userMapper.selectUserDtoByUserId(id);
        getUserPageInfo(loginUser, userDto, model);

        // 查询用户的粉丝
        List<UserDto> follows = followMapper.selectFollowedUsers(new UserQuery(userDto.getId(), null, 10));
        model.addAttribute("allFollows", follows);
        if (loginUser != null) {
            // 查询自己的关注列表
            List<Integer> followingIds = followMapper.selectFollowedIds(loginUser.getId());
            follows.forEach(item -> item.setFollow(followingIds.contains(item.getId())));
        }
        return "user/user-follows";
    }

    @ResponseBody
    @GetMapping("/moreFans")
    public ResponseDto loadMoreFans(@RequestParam("followerId") Integer followerId,
                                @RequestParam("userId") Integer userId,
                                HttpSession session) {
        UserDto loginUser = (UserDto) session.getAttribute("user");
        QueryWrapper<Follow> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("follower_id", followerId).eq("followed_id", userId);
        Follow follow = followMapper.selectOne(queryWrapper);
        // 查询用户的粉丝
        List<UserDto> fans = followMapper.selectMoreFans(new UserQuery(userId, follow.getId(), 10));
        if (loginUser != null) {
            // 查询自己的关注列表
            List<Integer> followingIds = followMapper.selectFollowedIds(loginUser.getId());
            fans.forEach(item -> item.setFollow(followingIds.contains(item.getId())));
        }
        return ResponseDto.Success("查询成功！", fans);
    }

    @ResponseBody
    @GetMapping("/moreFollows")
    public ResponseDto loadMoreFollows(@RequestParam("followedId") Integer followedId,
                                    @RequestParam("userId") Integer userId,
                                    HttpSession session) {
        UserDto loginUser = (UserDto) session.getAttribute("user");
        QueryWrapper<Follow> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("follower_id", userId).eq("followed_id", followedId);
        Follow follow = followMapper.selectOne(queryWrapper);
        // 查询用户的粉丝
        List<UserDto> follows = followMapper.selectMoreFollowedUsers(new UserQuery(userId, follow.getId(), 10));
        if (loginUser != null) {
            // 查询自己的关注列表
            List<Integer> followingIds = followMapper.selectFollowedIds(loginUser.getId());
            follows.forEach(item -> item.setFollow(followingIds.contains(item.getId())));
        }
        return ResponseDto.Success("查询成功！", follows);
    }


    public void getUserPageInfo(UserDto loginUser, UserDto userDto, Model model) {
        // 查询用户的帖子数量
        userDto.setCommentNumber(dynamicCommentMapper.selectDynamicCommentNumberByUserId(userDto.getId()));
        // 查询用户的评论数量
        userDto.setDynamicNumber(dynamicMapper.selectDynamicNumberByUserId(userDto.getId()));
        // 查询用户的粉丝
        List<UserDto> fans = followMapper.selectFans(new UserQuery(userDto.getId(), null, 5));
        // 查询用户的关注数量
        userDto.setFollowNumber(followMapper.selectFollowNumber(userDto.getId()));
        // 查询用户的粉丝数量
        userDto.setFanNumber(followMapper.selectFanNumber(userDto.getId()));
        // 查询用户的关注列表
        List<UserDto> follows = followMapper.selectFollowedUsers(new UserQuery(userDto.getId(), null, 5));
        if (loginUser != null) {
            // 查询该用户是否为自己关注
            userDto.setFollow(kkBlogService.ifFollow(loginUser.getId(), userDto.getId()));
            // 查询被访问用户是否是自己
            userDto.setMe(Objects.equals(loginUser.getId(), userDto.getId()));
            // 查询自己的关注列表
            List<Integer> followingIds = followMapper.selectFollowedIds(loginUser.getId());
            // 查询用户在自己的关注列表
            fans.forEach(item -> item.setFollow(followingIds.contains(item.getId())));
            follows.forEach(item -> item.setFollow(followingIds.contains(item.getId())));
        }
        model.addAttribute("fans", fans);
        model.addAttribute("follows", follows);
        model.addAttribute("userDto", userDto);
    }

    @GetMapping("/{id}")
    public String userPage(@PathVariable Integer id, HttpSession session, Model model) {
        UserDto loginUser = (UserDto) session.getAttribute("user");
        UserDto userDto = userMapper.selectUserDtoByUserId(id);
        // 查询用户的动态
        List<DynamicPreDto> dynamics = dynamicMapper.selectByUserId(id);
        if (loginUser != null) {
            // 查询是否对用户的动态点赞
            dynamics.forEach(item -> {
                item.setLiked(likeMapper.selectIfUserLike(loginUser.getId() + "_" + item.getId()) > 0);
            });
        }
        getUserPageInfo(loginUser, userDto, model);
        model.addAttribute("dynamics", dynamics);
        return "user/user";
    }

    @ResponseBody
    @GetMapping("/more")
    public ResponseDto loadMore(@RequestParam("dynamicId") Integer dynamicId,
                                @RequestParam("userId") Integer userId,
                                HttpSession session) {
        UserDto user = (UserDto) session.getAttribute("user");
        List<DynamicPreDto> dynamicPreDtos = kkBlogService.selectMoreDynamicsByUserId(userId, dynamicId);
        if (user != null) {
            dynamicPreDtos.forEach(item -> item.setLiked(likeMapper.selectIfUserLike(user.getId() + "_" + item.getId()) > 0));
        }
        return ResponseDto.Success("查询成功！", dynamicPreDtos);
    }
}
